package com.handpay.zztong.hp.onlineshop.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.MD5;
import com.handpay.framework.SecureManager;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.framework.swiper.ApiSwiperFactory;
import com.handpay.framework.swiper.SwiperMode;
import com.handpay.framework.utils.ArithUtil;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.Heart;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.bean.Rate;
import com.handpay.zztong.hp.bean.Rates;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;

import com.handpay.zztong.hp.main.model.lowestamount.LowestAccountTransferAmount;
import com.handpay.zztong.hp.main.model.lowestamount.LowestAmountModel;
import com.handpay.zztong.hp.main.model.ratelist.RateListBean;
import com.handpay.zztong.hp.main.model.ratelist.RateListModel;
import com.handpay.zztong.hp.main.widget.RateDialogFragment;
import com.handpay.zztong.hp.onlineshop.model.marketorder.MarketOrderDetailBean;
import com.handpay.zztong.hp.onlineshop.model.marketorder.MarketOrderDetailModel;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.swiper.activity.VPOSActivity;
import com.handpay.zztong.hp.ui.MoneyEdit;
import com.handpay.zztong.hp.ui.ZZTShowDialog;
import com.handpay.zztong.hp.utils.AccountUtils;

import java.util.Hashtable;
import java.util.Map;

import se.krka.kahlua.vm.LuaTable;


public class ShowMarketHtmlActivity extends ZZTongActivity implements OnClickListener, ApiNoticeListener,RateDialogFragment.OnRateViewButtonLinsener {

    /**
     * 页面标题
     */
    public static final String ShowHtml_Title_Key = "ShowHtml_Title_Key";

    /**
     * 要显示的html路径
     */
    public static final String ShowHtml_Html_Path_Key = "ShowHtml_Html_Path_Key";
    /**
     * 加载网页的webview
     */
    public WebView webView;
    /**
     * 网页加载的地址
     */
    private String mallUrl;

    //订单号
    private String orderNo;
    //转账流水号
    private String transSeq;
    private MoneyEdit amount_et;
    private String orderID;
    private String orderTime;
    private Double lowestAmount = 0d;
    private ZZTShowDialog mShowMarketDialog;
    private Rates rates;
    private Rate currentSelectRate=null;//当前选择的费率
    private Double selectAmount = 0d;
    private RateListModel ratemodle=null;
    private MarketOrderDetailModel marketmodle=null;
    private LowestAmountModel mLowestAmountModel;
    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    protected boolean isShownTopBar() {
        return false;
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_show_market_html);
        super.onCreate(savedInstanceState);
        if(marketmodle==null)
        {
            marketmodle=new MarketOrderDetailModel();
        }
        if(ratemodle==null)
        {
            ratemodle=new RateListModel();
        }
        if(mLowestAmountModel==null)
        {
            mLowestAmountModel=new LowestAmountModel();
        }
        findViewById(R.id.btn_goToFunction).setOnClickListener(this);
        webView = ((WebView) findViewById(R.id.userServiceWebView));
        webView.getSettings().setLoadsImagesAutomatically(true);
        final ProgressBar progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
        // 允许使用JS
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 禁用web view 的滚动条，否则右侧会有白边
        webView.setHorizontalScrollBarEnabled(true);
        webView.setVerticalScrollBarEnabled(false);
        webView.requestFocus();
        mallUrl = getIntent().getStringExtra(ShowHtml_Html_Path_Key);
        HPLog.i("ShowHtmlActivity", "mallUrl:" + mallUrl);
        webView.loadUrl(mallUrl);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http://handpay/orderPayment")) {
                    //supplierCode=xxx&orderID=xxx&orderTime=xxx&signData=xxx";
                    Map<String, String> map = CommonUtils.getUrlParamsMap(url);
                    String supplierCode = map.get("supplierCode");
                    orderID = map.get("orderID");
                    orderTime = map.get("orderTime");
                    String signData = map.get("signData");
                    String key = supplierCode + "|" + orderID + "|" + orderTime + "|" + AccountUtils.getAccountName(ShowMarketHtmlActivity.this);
                    String token = MD5.toMD5(key);
                    if (signData.equals(token)) {
                        doMarketOrderDetailByOrderId(orderID, orderTime);
                    }
                } else {
                    view.loadUrl(url);
                }
                return true;
            }


        });
//    	    }
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress >= 100) {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });
//        createFloatView();
        handle = new mHandler();
        ApiNoticeFactory.getInstance().registerApiNoticeListener(this);
        getLowestAccountTransferAmount();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_goToFunction) {
//            onFunctionTab(null);
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ApiNoticeFactory.getInstance().unregisterApiNoticeListener(this);
    }

    /**
     * 获取订单信息
     *
     * @param orderID   订单ID
     * @param orderTime 订单时间
     */
    public void doMarketOrderDetailByOrderId(String orderID, String orderTime) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("orderID", SecureManager.getInstance().des(orderID, 1, null)); // 交易流水
        params.put("orderTime", SecureManager.getInstance().des(orderTime, 1, null)); // 交易流水
//        doJsonPost(this, Do_GetMarketOrderDetailByOrderId, MarketOrderDetailBean.class, params);
        marketmodle.doMarketOrderDetailPost(this, params, new BusinessEngineListener<MarketOrderDetailBean>() {
            @Override
            public void callbackBusinessResponse(MarketOrderDetailBean marketOrderDetail) {
                if(marketOrderDetail!=null)
                    orderNo = SecureManager.getInstance().des(marketOrderDetail.getOrderNo(), 0, null);
                    String amount = SecureManager.getInstance().des(marketOrderDetail.getAmount(), 0, null);
                    transSeq = SecureManager.getInstance().des(marketOrderDetail.getTransSeq(), 0, null);
                    String goodsName = SecureManager.getInstance().des(marketOrderDetail.getGoodsName(), 0, null);
                    if (mShowMarketDialog == null) {
                        mShowMarketDialog = new ZZTShowDialog(ShowMarketHtmlActivity.this, R.layout.dialog_market, R.style.DialogSlideAnim);
                        Window window = mShowMarketDialog.getDialog().getWindow();
                        window.setGravity(Gravity.BOTTOM);
                        window.setBackgroundDrawableResource(android.R.color.transparent);
                        WindowManager.LayoutParams lp = window.getAttributes();
                        lp.width = screenWidth;
                        window.setAttributes(lp);
                        mShowMarketDialog.setDialogCallback(new ZZTShowDialog.Dialogcallback() {
                            @Override
                            public void ButtonOk() {
                                if (TextUtils.isEmpty(amount_et.getText())) {
                                    Toast.makeText(ShowMarketHtmlActivity.this, getString(R.string.enter_amount), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                selectAmount=Double.valueOf(amount_et.getText().toString());
                                if ((selectAmount*100) < lowestAmount) {
                                    Toast.makeText(ShowMarketHtmlActivity.this, getString(R.string.min_transfer_alert, lowestAmount.doubleValue() / 100), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                mShowMarketDialog.dismiss();
                                getMuiltRate(selectAmount);
                            }
                            @Override
                            public void ButtonCancle() {
                                mShowMarketDialog.dismiss();
                            }
                        });
                    }
                    TextView goods_name_tv = (TextView) mShowMarketDialog.getDialog().findViewById(R.id.goods_name_tv);
                    amount_et = (MoneyEdit) mShowMarketDialog.getDialog().findViewById(R.id.amount_et);
                    TextView order_no_tv = (TextView) mShowMarketDialog.getDialog().findViewById(R.id.order_no_tv);
                    amount_et.setText("");
                    goods_name_tv.setText(goodsName);
                    order_no_tv.setText(orderNo);
                    mShowMarketDialog.show();
            }
        });
    }

    /**
     * 获取交易限额
     */
    private void getLowestAccountTransferAmount() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("version", ClientEngine.VERSION);
        params.put("platform", ClientEngine.MOBILETYPE);
        params.put("channel", ClientEngine.CHANNEL);
//        doJsonPost(this, Do_GetLowestAccountTransferAmount, LowestAccountTransferAmount.class, params);
        mLowestAmountModel.domLowestAmountModelPost(this, params, new BusinessEngineListener<LowestAccountTransferAmount>() {
            @Override
            public void callbackBusinessResponse(LowestAccountTransferAmount bean) {
                if(bean!=null){
                    lowestAmount = CommonUtils.objectToDouble(bean.getAmount());
                }
            }
        });
    }

    public void goTo_VPOS_Activity() {
        setMode(SwiperMode.NORMAL_TRANS, false, new Runnable() {
            @Override
            public void run() {
                goToVPos();
            }
        });
    }

    private void getMuiltRate(double amount) {
        HPLog.i(HPLog.TAG_RESULT,"----getMuiltRate--amount:"+amount);
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("version", ClientEngine.VERSION);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put("businessType", "1");
        params.put("amount", SecureManager.getInstance().des(ArithUtil.mul(amount, 100d) + "", 1, null));
        ratemodle.doRateListPost(this, params, new BusinessEngineListener<RateListBean>() {
            @Override
            public void callbackBusinessResponse(RateListBean bean) {
                rates = Rates.generateRates(bean);
//            rates=Rates.generateTestRates();
                HPLog.i(HPLog.TAG_RESULT,"rates.size："+rates.getRates().size());
                if (!rates.isRateNull()) {
                    showRateListView();
                } else {
                    goTo_VPOS_Activity();
                }
            }
        });
    }

    private void showRateListView(){
        RateDialogFragment.newInstance(getString(R.string.hint_titile_rate),rates,false,this).show(getFragmentManager(),"rate");
    }
    @Override
    public void goToVPos() {
        super.goToVPos();
        if (checkVPOS(ShowMarketHtmlActivity.this, true)) {
            ApiSwiperFactory.getInstance().setMode(SwiperMode.NORMAL_TRANS);
            Hashtable<String, Object> params = new Hashtable<String, Object>();
            params.put(ZZTongActivity.ACTION, ZZTongActivity.Action_MARKET);
            params.put(VPOSActivity.Transfer_Amount_Key, ArithUtil.mul(selectAmount, 100d));
            params.put("isRateNull", rates.isRateNull());
            if(!rates.isRateNull()&&currentSelectRate!=null){
                HPLog.i(HPLog.TAG_RESULT,"rates:"+rates.toString());
                params.put("selectedRate", currentSelectRate.getRateCodeId());
                params.put("isPublicCharge", currentSelectRate.getIsPublicChargeId());
            }
            params.put("orderNo", orderNo);
            params.put("transSeq", transSeq);
            startActivity(ShowMarketHtmlActivity.this, VPOSActivity.class, params);
        }
    }

    @Override
    public void onNotifyNotice(int action, Bundle bundle) {
//        http://10.148.181.152:8092/pay/HyPayResult.aspx?status=1&orderID=267&orderTime=20160804174132
        String pageUrl = bundle.getString("pageUrl");
        String status = bundle.getString("status");
        pageUrl = pageUrl + "?status=" + status + "&orderID=" + orderID + "&orderTime=" + orderTime;
        HPLog.i(HPLog.YL_TAG, "pageUrl:" + pageUrl);
        webView.loadUrl(pageUrl);
    }

    @Override
    public int[] getNoticeAction() {
        int actions[] = {MARKET_ACTION};
        return actions;
    }

    private WindowManager mWindowManager;
    private WindowManager.LayoutParams wmParams;
    private LinearLayout mFloatLayout;
    private ImageView market_exit_btn;
    private int xlocation, ylocation, xDownLocation, yDownLocation;
    private static final int toleft = 1;
    private static final int toright = 2;
    private mHandler handle;

    private void createFloatView() {
        //获取LayoutParams对象
        wmParams = new WindowManager.LayoutParams();
        //获取的是LocalWindowManager对象
        mWindowManager = this.getWindowManager();
        //获取的是CompatModeWrapper对象
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        wmParams.format = PixelFormat.RGBA_8888;
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        //设置初始位置
        wmParams.x = 0;
        final int top = 120;
        final int bottom = Heart.displayHeightPixels - 500;
        wmParams.y = bottom;
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.show_martket_html_exit, null);
        mWindowManager.addView(mFloatLayout, wmParams);
        market_exit_btn = (ImageView) mFloatLayout.findViewById(R.id.market_exit_btn);
        market_exit_btn.setOnClickListener(this);
        market_exit_btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        xDownLocation = (int) event.getRawX();
                        yDownLocation = (int) event.getRawY();
                        return false;
                    case MotionEvent.ACTION_MOVE:
                        xlocation = (int) event.getRawX();
                        ylocation = (int) event.getRawY();
                        wmParams.x = xlocation - mFloatLayout.getWidth() / 2;
                        int tmpYLocation = ylocation - mFloatLayout.getHeight() / 2;
                        if (tmpYLocation > bottom) {
                            wmParams.y = bottom;
                        } else if (tmpYLocation < top) {
                            wmParams.y = top;
                        } else {
                            wmParams.y = tmpYLocation;
                        }
                        mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                        return false;
                    case MotionEvent.ACTION_UP:
//                        if (xlocation > Heart.displayWidthPixels / 2) {
//                            handle.sendEmptyMessage(toright);
//                        } else {
                        handle.sendEmptyMessage(toleft);
//                        }
                        int _x = Math.abs(xDownLocation - xlocation);
                        int _y = Math.abs(yDownLocation - ylocation);
                        if (Math.sqrt(_x * _x + _y * _y) < 6) {
                            return false;
                        } else {
                            return true;
                        }

                    default:
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void onOkClick(Dialog dialog, Rate obj) {
        HPLog.i(HPLog.TAG_RESULT,obj!=null?obj.toString():"Error：Rate 对象为null！");
        String temp=obj!=null?obj.getRateAmount():null;
        if(TextUtils.isEmpty(temp)){
            Toast.makeText(this,getString(R.string.hint_data_exception),Toast.LENGTH_LONG).show();
            return;
        }
        dialog.cancel();
        //如果大于0 则继续判断金额
        if(CommonUtils.objectToInt(temp)>0&&(selectAmount*100)>Double.parseDouble(temp)){
            showAlertDialog(this,this.getString(R.string.tip),this.getString(R.string.hint_limit_money,(Double.parseDouble(temp)/100)),true,new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            return;
        }
        currentSelectRate=obj;
        goTo_VPOS_Activity();
    }

    class mHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case toleft:
                    wmParams.x -= 30;
                    if (wmParams.x >= 0) {
                        mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                        handle.sendEmptyMessageDelayed(toleft, 1);

                    } else {
                        wmParams.x = 0;
                        mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                    }
                    break;
                case toright:
                    wmParams.x += 30;
                    if (wmParams.x <= Heart.displayWidthPixels) {
                        mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                        handle.sendEmptyMessageDelayed(toright, 1);
                    } else {
                        wmParams.x = Heart.displayWidthPixels;
                        mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
